#!/bin/bash

while ! nc -z $DB_HOST $DB_PORT;
do
    echo "wait for bees_mysql ${DB_HOST} ready"
    sleep 2s
done

while ! nc -z $REDIS_HOST $REDIS_PORT;
do
    echo "wait for bees_redis ${REDIS_HOST} ready"
    sleep 2s
done

action="${1-start}"
if [ ! "${action}" ]; then
  action=start
fi

service="${2-all}"
if [ ! "${service}" ]; then
  service=all
fi

echo ">>> " $0 $action $service

if [[ "$action" == "bash" || "$action" == "sh" ]];then
    /bin/bash
elif [[ "$action" == "python" ]]; then
    . /opt/py3/bin/activate
    cd /opt/bees
    export FLASK_APP=apps/manage.py
    flask shell
elif [[ "$action" == "upgrade_db" ]];then
    . /opt/py3/bin/activate
    cd /opt/bees
    export FLASK_APP=apps/manage.py
    flask db migrate
    sleep 3
    flask db upgrade
elif [[ "$action" == "init_db" ]];then
    . /opt/py3/bin/activate
    cd /opt/bees
    export FLASK_APP=apps/manage.py
    flask db migrate
    sleep 3
    flask db upgrade
    sleep 3
    flask init
else
    . /opt/py3/bin/activate
    cd /opt/bees
    python3 ./bees.py "${action}" "${service}"
fi
